<template>
  <div class="table-stats-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-page-header @back="goBack" :content="pageTitle">
        <template #icon>
          <el-icon><ArrowLeft /></el-icon>
        </template>
      </el-page-header>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-row">
        <div class="filter-item">
          <label>时间范围:</label>
          <el-radio-group v-model="filters.days" @change="loadStats">
            <el-radio-button :label="7">近7天</el-radio-button>
            <el-radio-button :label="30">近30天</el-radio-button>
            <el-radio-button :label="90">近90天</el-radio-button>
          </el-radio-group>
        </div>

        <div class="filter-item">
          <label>统计类型:</label>
          <el-radio-group v-model="filters.stat_type" @change="loadStats">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="hourly">小时统计</el-radio-button>
            <el-radio-button label="manual">手动统计</el-radio-button>
          </el-radio-group>
        </div>

        <div class="filter-item">
          <el-button @click="loadStats" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 图表展示 -->
    <div class="charts-container" v-loading="loading">
      <!-- 数据行数趋势 -->
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="chart-header">
            <el-icon><DataLine /></el-icon>
            <span>数据行数趋势</span>
          </div>
        </template>
        <div ref="rowsChartRef" class="chart"></div>
      </el-card>

      <!-- 数据大小趋势 -->
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="chart-header">
            <el-icon><Files /></el-icon>
            <span>数据大小趋势</span>
          </div>
        </template>
        <div ref="sizeChartRef" class="chart"></div>
      </el-card>

      <!-- 增量变化趋势（三增量设计） -->
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="chart-header">
            <el-icon><TrendCharts /></el-icon>
            <span>三增量趋势（上次/当前/总计）</span>
          </div>
        </template>
        <div ref="incrementChartRef" class="chart"></div>
      </el-card>
    </div>

    <!-- 统计数据表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="table-header">
          <span>
            <el-icon><List /></el-icon>
            统计记录明细 ({{ stats.length }})
          </span>
        </div>
      </template>

      <el-table :data="stats" height="400" size="small">
        <el-table-column prop="stat_time" label="统计时间" width="180" />
        <el-table-column prop="stat_type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatTypeTag(row.stat_type)" size="small">
              {{ getStatTypeLabel(row.stat_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total_rows" label="总行数" width="120">
          <template #default="{ row }">
            {{ formatNumber(row.total_rows) }}
          </template>
        </el-table-column>
        <el-table-column prop="data_length" label="数据大小" width="120">
          <template #default="{ row }">
            {{ formatBytes(row.data_length) }}
          </template>
        </el-table-column>
        <el-table-column prop="previous_increment_rows" label="上次增量" width="100">
          <template #default="{ row }">
            <span :class="getIncrementClass(row.previous_increment_rows)">
              {{ formatIncrement(row.previous_increment_rows) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="current_increment_rows" label="当前增量" width="100">
          <template #default="{ row }">
            <span :class="getIncrementClass(row.current_increment_rows)">
              {{ formatIncrement(row.current_increment_rows) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="total_increment_rows" label="总增量(当天)" width="120">
          <template #default="{ row }">
            <span :class="getIncrementClass(row.total_increment_rows)">
              {{ formatIncrement(row.total_increment_rows) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="collection_method" label="收集方式" width="150" />
        <el-table-column prop="collection_duration_ms" label="耗时" width="100">
          <template #default="{ row }">
            {{ row.collection_duration_ms }}ms
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft, Refresh, DataLine, Files, TrendCharts, List, Download
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import api from '@/utils/api'
import { logger } from '@/utils/logger'

const route = useRoute()
const router = useRouter()

// 响应式数据
const tableId = ref(parseInt(route.params.id))
const tableName = ref('')
const loading = ref(false)
const stats = ref([])
const filters = reactive({
  days: 30,
  stat_type: ''
})

// 图表实例
const rowsChartRef = ref(null)
const sizeChartRef = ref(null)
const incrementChartRef = ref(null)
let rowsChart = null
let sizeChart = null
let incrementChart = null

// 页面标题
const pageTitle = computed(() => {
  return tableName.value ? `${tableName.value} - 统计历史` : '统计历史'
})

// 格式化函数 - 使用中文单位（支持负数）
const formatNumber = (num) => {
  if (!num) return '0'
  
  // 处理负数：保留符号，用绝对值计算单位
  const isNegative = num < 0
  const absNum = Math.abs(num)
  const sign = isNegative ? '-' : ''
  
  if (absNum >= 1e8) {
    const value = absNum / 1e8
    return sign + (value >= 10 ? Math.round(value) + '亿' : value.toFixed(1) + '亿')
  }
  if (absNum >= 1e4) {
    const value = absNum / 1e4
    return sign + (value >= 10 ? Math.round(value) + '万' : value.toFixed(1) + '万')
  }
  return num.toLocaleString('zh-CN')
}

const formatBytes = (bytes) => {
  if (!bytes) return '0 B'
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i]
}

const formatIncrement = (increment) => {
  if (!increment) return '0'
  const sign = increment > 0 ? '+' : ''
  return sign + formatNumber(increment)
}

const getIncrementClass = (increment) => {
  if (increment > 0) return 'positive'
  if (increment < 0) return 'negative'
  return 'zero'
}

const getStatTypeTag = (type) => {
  const types = {
    'hourly': 'success',    // 绿色 - 定时任务
    'manual': 'warning'     // 橙色 - 手动操作
  }
  return types[type] || 'info'
}

const getStatTypeLabel = (type) => {
  const labels = {
    'hourly': '小时统计',
    'manual': '手动统计'
  }
  return labels[type] || type
}

// 初始化图表
const initCharts = () => {
  if (rowsChartRef.value) {
    rowsChart = echarts.init(rowsChartRef.value)
  }
  if (sizeChartRef.value) {
    sizeChart = echarts.init(sizeChartRef.value)
  }
  if (incrementChartRef.value) {
    incrementChart = echarts.init(incrementChartRef.value)
  }

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  rowsChart?.resize()
  sizeChart?.resize()
  incrementChart?.resize()
}

// 更新图表
const updateCharts = () => {
  if (stats.value.length === 0) return

  // 反转数据，按时间正序
  const reversedStats = [...stats.value].reverse()
  const times = reversedStats.map(s => s.stat_time.substring(5, 16)) // MM-DD HH:mm
  
  // 数据行数趋势图
  const rowsOption = {
    title: {
      text: '数据行数',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const data = params[0]
        return `${data.axisValue}<br/>总行数: ${formatNumber(data.value)}`
      }
    },
    xAxis: {
      type: 'category',
      data: times,
      axisLabel: { rotate: 45, fontSize: 10 }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => formatNumber(value)
      }
    },
    series: [{
      name: '总行数',
      type: 'line',
      data: reversedStats.map(s => s.total_rows),
      smooth: true,
      areaStyle: { opacity: 0.3 },
      itemStyle: { color: '#409eff' }
    }],
    grid: {
      left: '60px',
      right: '20px',
      bottom: '60px'
    }
  }

  // 数据大小趋势图
  const sizeOption = {
    title: {
      text: '数据大小',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const data = params[0]
        return `${data.axisValue}<br/>数据大小: ${formatBytes(data.value)}`
      }
    },
    xAxis: {
      type: 'category',
      data: times,
      axisLabel: { rotate: 45, fontSize: 10 }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => formatBytes(value)
      }
    },
    series: [{
      name: '数据大小',
      type: 'line',
      data: reversedStats.map(s => s.data_length),
      smooth: true,
      areaStyle: { opacity: 0.3 },
      itemStyle: { color: '#67c23a' }
    }],
    grid: {
      left: '60px',
      right: '20px',
      bottom: '60px'
    }
  }

  // 三增量趋势图
  const incrementOption = {
    title: {
      text: '三增量趋势（上次/当前/总计）',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        let result = `${params[0].axisValue}<br/>`
        params.forEach(p => {
          result += `${p.marker}${p.seriesName}: ${formatIncrement(p.value)}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['上次增量', '当前增量', '总增量(当天)'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: times,
      axisLabel: { rotate: 45, fontSize: 10 }
    },
    yAxis: {
      type: 'value',
      name: '行数',
      axisLabel: { formatter: (value) => formatNumber(value) }
    },
    series: [
      {
        name: '上次增量',
        type: 'line',
        data: reversedStats.map(s => s.previous_increment_rows || 0),
        smooth: true,
        itemStyle: { color: '#909399' }
      },
      {
        name: '当前增量',
        type: 'bar',
        data: reversedStats.map(s => s.current_increment_rows || 0),
        itemStyle: { color: '#e6a23c' }
      },
      {
        name: '总增量(当天)',
        type: 'line',
        data: reversedStats.map(s => s.total_increment_rows || 0),
        smooth: true,
        areaStyle: { opacity: 0.2 },
        itemStyle: { color: '#67c23a' }
      }
    ],
    grid: {
      left: '60px',
      right: '60px',
      bottom: '60px',
      top: '80px'
    }
  }

  rowsChart?.setOption(rowsOption)
  sizeChart?.setOption(sizeOption)
  incrementChart?.setOption(incrementOption)
}

// 加载统计数据
const loadStats = async () => {
  loading.value = true
  try {
    const params = {
      days: filters.days
    }
    if (filters.stat_type) {
      params.stat_type = filters.stat_type
    }

    const response = await api.get(`/starrocks-tables/tables/${tableId.value}/stats/history`, { params })
    
    if (response.data.success) {
      stats.value = response.data.data.stats || []
      if (stats.value.length > 0) {
        tableName.value = `${stats.value[0].database_name}.${stats.value[0].table_name}`
      }
      
      // 更新图表
      updateCharts()
    }
  } catch (error) {
    logger.error('加载统计历史失败:', error)
    ElMessage.error('加载统计历史失败')
  } finally {
    loading.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 生命周期
onMounted(() => {
  initCharts()
  loadStats()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  rowsChart?.dispose()
  sizeChart?.dispose()
  incrementChart?.dispose()
})
</script>

<style scoped>
.table-stats-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-card {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 24px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-item label {
  font-weight: 500;
  color: #606266;
  white-space: nowrap;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  min-height: 400px;
}

.chart-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #2c3e50;
}

.chart {
  width: 100%;
  height: 350px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header span {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #2c3e50;
}

.positive { color: #67c23a; }
.negative { color: #f56c6c; }
.zero { color: #909399; }

:deep(.el-page-header__content) {
  font-size: 18px;
  font-weight: 600;
}
</style>

